const express = require("express")
const ViteExpress = require("vite-express")
const path = require('path');
const customPath = path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`);
require('dotenv').config({ path: customPath });
const mongoose = require('mongoose');
const schedule = require('node-schedule');
const compression = require("compression");
const {executeWithRetry} = require("./utils/index.js");

// 创建定时任务
// 格式：分 时 日 月 星期（0-6 表示周日到周六）
const job = schedule.scheduleJob('30 15 * * 1-5',async ()=> {
  console.log(`[${new Date().toISOString()}] 开始执行每日生成任务`);
  let url = `http://127.0.0.1:${process.env.PORT}/api/tuyere/excute`;
  try {
    await executeWithRetry(url);
  } catch (error) {
    console.error(`[${new Date().toISOString()}] 每日生成任务执行失败:`, error.message);
  }

});


const app = express();
app.use(express.json());

mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}) .then(() => console.log('MongoDB连接成功'))
  .catch(err => {
    console.error('MongoDB连接失败:', err);
    process.exit(1); // 连接失败时退出应用
});


if (process.env.ENV === 'production'){
  app.use(compression());
}

const apiRegister = require("./src/api/index.js");

apiRegister(app)

process.on('SIGINT', async () => {
    await mongoose.connection.close();
    job.cancel();
    process.exit();
});

ViteExpress.config({ mode: process.env.ENV })


ViteExpress.listen(app, process.env.PORT, () =>
  console.log("Server is listening on " + process.env.PORT),
);

